<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>小区地图</title>
    <link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
    <style type="text/css">

        #panel {
            position: absolute;
            background-color: white;
            max-height: 90%;
            overflow-y: auto;
            top: 120px;
            right: 20px;
            width: 200px;
        }

        .amap-marker .marker-route {
            position: absolute;
            width: 40px;
            height: 44px;
            color: #e90000;
            background: url(http://webapi.amap.com/theme/v1.3/images/newpc/poi-1.png) no-repeat;
            cursor: pointer;
        }

        .amap-marker .marker-marker-bus-from {
            background-position: -334px -180px;
        }

        input[type="text"] {
            height: 25px;
            outline: none;
            border: 0;
            border: 1px solid #CCCCCC;
            padding: 0 4px;
        }

        .taiwan {
            height: 100%;
            margin: 0px;
            font: 12px Arial;
            border: solid 1px red;
            color: red;
            float: left;
            width: 50px;
            background-color: rgba(255, 0, 0, 0.1)
        }

    </style>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script>
    <script type="text/javascript"
            src="http://webapi.amap.com/maps?v=1.3&key=28be1a8e873757a3a359cf61e6e1e5f1"></script>
    <script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id="container"></div>

<div id="tip">
    <div id="myPageTop">
        <table>
            <tr>
                <td>
                    <input type="text" placeholder="请输入关键字进行搜索" id="tipinput">
                </td>
                <td class="column2">
                    <input type="text" readonly="true" id="lnglat">
                </td>
            </tr>
            <tr>
                <span id="info"></span>
            </tr>
        </table>
    </div>
</div>
<div id="panel"></div>
<div class="button-group">
    <tb>
        <td>
            <input id="cityName" class="inputtext" placeholder="请输入城市的名称" type="text"/>
            <input id="query" class="button" value="到指定的城市" type="button"/>
        </td>
        <td>
            <input id="communityName" class="inputtext" placeholder="请输入关键字对小区搜索" type="text"/>
            <input id="communitySearch" class="button" value="搜索小区" type="button"/></td>
        </td>
    </tb>

</div>

<script type="text/javascript" src="/pages/moderatorManager/js/province_data.js"></script>
<script type="text/javascript">
    var cloudDataLayer;
    var cluster, markers = [], markersCommunity = [], polygons = [];//行政区域边界划分
    var mousePointCity = {};
    var mousePointLocation = {};
    var provinceData = {};
    var cityData = {};
    var search;

    //缩放级别
    var communityScaleLevel = 10;
    var cityScaleLevel = 8;
    var provinceScaleLevel = 5;
    var communityAddress;

    //计算 地图分块后的步长
    var lngStep;
    var latStep;

    var isSubMarkersShow = false;
    var isSearchShow = false;
    var citySelect = document.getElementById('city');
    var districtSelect = document.getElementById('district');

    var tableId = '56b19e307bbf197f39989c1d';
    var mapCenter = [121.471271, 31.219375];//上海
    //地图初始化
    var map = new AMap.Map("container", {
        resizeEnable: true,
        dragEnable: true,//允许叠加地图热点
        keyboardEnable: true,
        center: mapCenter,//地图中心点
        zoom: provinceScaleLevel //地图显示的缩放级别zoom:5 省个数  10 区个数 12以上 小区位置显示
    });

    //加载行政区划插件
    AMap.service('AMap.DistrictSearch', function () {
        var opts = {
            subdistrict: 1,   //返回下一级行政区
            extensions: 'all',  //返回行政区边界坐标组等具体信息
            level: 'city'  //查询行政级别为 市
        };
        //实例化DistrictSearch
        district = new AMap.DistrictSearch(opts);
        district.setLevel('district');
    });

    function provinceArea(province) {
            //行政区查询
            district.search(province, function (status, result) {
                var bounds = result.districtList[0].boundaries;
                map.remove(polygons);
                if (bounds) {
                    for (var i = 0, l = bounds.length; i < l; i++) {
                        //生成行政区划polygon
                        var polygon = new AMap.Polygon({
                            map: map,
                            strokeWeight: 1,
                            path: bounds[i],
                            fillOpacity: 0.7,
                            fillColor: '#CCF3FF',
                            strokeColor: '#CC66CC'
                        });
                        polygons.push(polygon);
                    }
                }
            });
    }

    //添加信息窗体
    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});


    //省下 市点 初始化
    var createMarker = function (data, hide) {
        var marker = new AMap.Marker({
            title: data.name,
            icon: hide ? "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png" : "http://developer.amap.com/wp-content/uploads/2014/06/marker.png",
            position: [data.location.longitude - 0.0065, data.location.latitude - 0.0065],
        });

        marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
            offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
            content: hide ? data.count + "/" + data.all : data.count + ''
        });

        marker.subMarkers = [];
        if (data.subDistricts && data.subDistricts.length) {
            for (var i = 0; i < data.subDistricts.length; i += 1) {
                marker.subMarkers.push(createMarker(data.subDistricts[i], true));
            }
        }
        if (hide) {
            AMap.event.addListener(marker, 'click', markerCityClick);
        }
        return marker;
    }

    var _onClick = function (e) {
        if (e.target.subMarkers.length) {
            map.clearMap();
            isSubMarkersShow = true;
            provinceArea(e.target.getTitle());
            map.add(e.target.subMarkers);
            map.setFitView(e.target.subMarkers);//缩放到合适的级别 显示地图数据
            map.remove(markers)
        }
    };

    function markerCityClick(e) {
        provinceArea(e.target.getTitle())
        map.setZoom(communityScaleLevel);
    }

    //逆向地理位置编码
    function regeocoder(lnglatXY, callback) {                    //逆地理编码

        //var map = new AMap.Map("container");
        //步骤一：初始化地图，本步骤可不实现
        //步骤二：通过AMap.service加载检索服务，加载的服务可以包括服务插件列表中一个或多个
        AMap.service(["AMap.Geocoder"], function () { //加载地理编码
            geocoder = new AMap.Geocoder({
                radius: 1000,
                extensions: "all"
            });
            //步骤三：通过服务对应的方法回调服务返回结果，本例中通过逆地理编码方法getAddress回调结果
            geocoder.getAddress(lnglatXY, function (status, result) {
                //根据服务请求状态处理返回结果
                if (status == 'error') {
                    console.log("服务请求出错啦！ ");
                }
                if (status == 'no_data') {
                    console.log("无数据返回，请换个关键字试试～～");
                }
                else if (status === 'complete' && result.info === 'OK') {
                    console.log(result.regeocode.formattedAddress);
                    callback(result.regeocode.formattedAddress);    // 返回地址描述
                }
                else {
                    console.log(result);
                }
            });
        });
    }

    // 添加点聚合
    function addCluster(tag) {
        if (cluster) {
            cluster.setMap(null);
        }
        if (tag == 1) {
            var sts = [{
                url: "http://developer.amap.com/wp-content/uploads/2014/06/1.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -30)
            }, {
                url: "http://developer.amap.com/wp-content/uploads/2014/06/2.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -30)
            }, {
                url: "http://developer.amap.com/wp-content/uploads/2014/06/3.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -45),
                textColor: '#CC0066'
            }];
            map.plugin(["AMap.MarkerClusterer"], function () {
                cluster = new AMap.MarkerClusterer(map, markers, {
                    minClusterSize: 6,
                    styles: sts
                });
            });
        } else {
            map.plugin(["AMap.MarkerClusterer"], function () {
                cluster = new AMap.MarkerClusterer(map, markers, {minClusterSize: 6});
            });
        }
    }

    //小区 地理位置请求事件v2: 一块地图 被划分成6大块
    var getCommunityPart = function () {

//        var Loc = {
//            "NorthEast":[dataArea.northeast.lng,dataArea.northeast.lat], // 东北 右上角
//            "SouthWest":[dataArea.southwest.lng,dataArea.southwest.lat]} // 西南 左下角
        if (map.getZoom() >= communityScaleLevel) {
            var dataArea = map.getBounds();
            var southPoint = {lng: dataArea.southwest.lng, lat: dataArea.southwest.lat};
            if (!lngStep && !latStep) {
                lngStep = Math.abs(dataArea.southwest.lng - dataArea.northeast.lng);
                latStep = Math.abs(dataArea.southwest.lat - dataArea.northeast.lat);
            }

            var mapPart_1 = {
                "NorthEast": [southPoint.lng + lngStep, southPoint.lat + latStep],     // 东北 右上角// 西南 左下角
                "SouthWest": [southPoint.lng, southPoint.lat],
                "Loc2Address": communityAddress + 1
            }

            var mapPart_2 = {
                "NorthEast": [southPoint.lng + 2 * lngStep, southPoint.lat + 2 * latStep], // 东北 右上角// 西南 左下角
                "SouthWest": [southPoint.lng + lngStep, southPoint.lat + latStep],
                "Loc2Address": communityAddress + 2
            }
            var mapPart_3 = {
                "NorthEast": [southPoint.lng + 2 * lngStep, southPoint.lat + latStep],   // 东北 右上角 // 西南 左下角
                "SouthWest": [southPoint.lng + lngStep, southPoint.lat],
                "Loc2Address": communityAddress + 3
            }
            var mapPart_4 = {
                "NorthEast": [southPoint.lng + 3 * lngStep, southPoint.lat + latStep],   // 东北 右上角 // 西南 左下角
                "SouthWest": [southPoint.lng + 2 * lngStep, southPoint.lat],
                "Loc2Address": communityAddress + 4
            }
            var mapPart_5 = {
                "NorthEast": [southPoint.lng + 3 * lngStep, southPoint.lat + latStep * 2], // 东北 右上角// 西南 左下角
                "SouthWest": [southPoint.lng + 2 * lngStep, southPoint.lat + latStep],
                "Loc2Address": communityAddress + 5
            }
            var mapPart_6 = {
                "NorthEast": [southPoint.lng + 2 * lngStep, southPoint.lat + latStep],   // 东北 右上角// 西南 左下角
                "SouthWest": [southPoint.lng + lngStep, southPoint.lat],
                "Loc2Address": communityAddress + 6
            }

            var mapParts = [];
            mapParts.push(mapPart_1);
            mapParts.push(mapPart_2);
            mapParts.push(mapPart_3);
            mapParts.push(mapPart_4);
            mapParts.push(mapPart_5);
            mapParts.push(mapPart_6);

            if (markersCommunity.length > 500) {
                console.log(markersCommunity.length + "资源超支，正在删除");
                markersCommunity.splice(0, markersCommunity.length / 2);
            } else {
                console.log(markersCommunity.length + "资源超支，正在删除");
                markersCommunity.splice(0, markersCommunity.length / 10);
            }
            for (var count in mapParts) {
                console.log('当前请请求区域为' + mapParts[count]);
                console.log(mapParts[count]);
                $.ajax({
                    url: "/rest/v1.0/mis/community/communityByLocationList",
                    type: "post",
                    data: mapParts[count],
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        if (data.data.length == 0) {
                            console.log("该地区无小区，请重新刷新");
                        }
                        for (var count = 0; count < data.data.length; ++count) {
                            var markerPosition = [data.data[count].location.longitude, data.data[count].location.latitude];
                            var marker = new AMap.Marker({
                                position: markerPosition,
                                icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                                offset: {x: -8, y: -34}
                            });

//                            marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
//                                offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
//                                content:  data.data[count].persons?'0':data.data[count].persons+''
//                            });

                            marker.setMap(map);
                            markersCommunity.push(marker);
                        }
                    }
                });
            }
        }
    }

    //城市->省数据初始化 地理位置请求 测试环境365个城市
    var getAllCityInfo = function () {
        $.ajax({
            url: "/rest/v1.0/mis/community/communityCountList/city", success: function (data) {
                console.log(data);
                markers = [];
                cityData = data;
                for (var count = 0; count < data.data.length; ++count) {
                    if (provinceData[data.data[count].province]) {
                        provinceData[data.data[count].province].count += data.data[count].count;
                        provinceData[data.data[count].province].all += data.data[count].all;
                        provinceData[data.data[count].province].subDistricts.push(data.data[count]);
                    } else {
                        provinceData[data.data[count].province] = {};
                        provinceData[data.data[count].province].all = data.data[count].all;
                        provinceData[data.data[count].province].count = data.data[count].count;
                        provinceData[data.data[count].province].name = data.data[count].province;
                        provinceData[data.data[count].province].location = {};
                        try {
                            var location = provinces[data.data[count].province].center.split(',');
                            provinceData[data.data[count].province].location.longitude = parseFloat(location[0]);
                            provinceData[data.data[count].province].location.latitude = parseFloat(location[1]);
                        } catch (exception) {
                            console.log(data.data[count].province)
                            console.log(exception);
                        }

                        provinceData[data.data[count].province].subDistricts = [];
                        provinceData[data.data[count].province].subDistricts.push(data.data[count]);
                    }
                }
                mapProvinceSet();
            }
        });
    }

    //省
    var mapProvinceSet = function () {
        map.clearMap();
        markers = [];
        map.remove(polygons);
        for (var i in provinceData) {
            var marker = createMarker(provinceData[i]);
            marker.setMap(map);
            markers.push(marker);
            AMap.event.addListener(marker, 'click', _onClick);
        }
    }

    //市
    var mapCitySet = function () {
        map.remove(markers)
        markers = [];
        cloudDataLayer.setMap(null);

        for (var count in cityData.data) {
            var data = cityData.data[count];
            var marker = new AMap.Marker({
                title: data.name,
                icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                position: [data.location.longitude - 0.0065, data.location.latitude - 0.0065],
                offset: new AMap.Pixel(-24, 5),
            });

            marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
                offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
                content: data.count + "/" + data.all
            });

            marker.setMap(map);
            markers.push(marker);
            AMap.event.addListener(marker, 'click', markerCityClick);
        }

    }

    //地图 初始化
    var mapInit = function () {
        getAllCityInfo();
    }

    //小区麻点图 初始化
    var mapCommunityCloudInit = function () {
        AMap.plugin('AMap.CloudDataLayer', function () {
            var layerOptions = {
//                query: {keywords: '公园'},
                clickable: true
            };
            cloudDataLayer = new AMap.CloudDataLayer(tableId, layerOptions);

            AMap.event.addListener(cloudDataLayer, 'click', function (result) {

                var clouddata = result.data;
                var infoWindow = new AMap.InfoWindow({
                    content: "<h3><font face='微软雅黑'color='#36F'>" +
                    clouddata._name + "</font></h3><hr />地址：" +
                    clouddata._address + "<br />" + "创建时间：" +
                    clouddata._createtime + "<br />" + "更新时间：" +
                    clouddata._updatetime,
                    size: new AMap.Size(300, 0),
                    autoMove: true,
                    offset: new AMap.Pixel(0, -25)
                });
                infoWindow.open(map, clouddata._location);

            });
        })
    }

    //移动设备下有效的
    var touchendEventListener = map.on('touchend', function (e) {
        document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
//        getCommunityPart();
    })

    //地图平移结束后触发。如地图有拖拽缓动效果，则在缓动结束后触发
    var mousedownEventListener = map.on('mousedown', function (e) {
        console.log('鼠标按下了');
        if (e) {
            document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
            mousePointLocation.lng = e.lnglat.getLng();
            mousePointLocation.lat = e.lnglat.getLat();
            regeocoder([e.lnglat.getLng(), e.lnglat.getLat()], function (data) {
                communityAddress = data;
                document.getElementById("tipinput").value = data;
            });
        }
    });

    var moveendEventListener = map.on('moveend', function () {
        console.log('地图移动结束');
//        getCommunityPart()
    });

    //缩放结束事件
    var zoomendEventListener = AMap.event.addListener(map, 'zoomend', function () {
        document.getElementById('info').innerHTML = '当前缩放级别：' + map.getZoom();

        if (map.getZoom() >= communityScaleLevel && !isSearchShow) {
            if (cloudDataLayer) {
                cloudDataLayer.setMap(map);
            } else {
                mapCommunityCloudInit();
            }
        }
        else if (map.getZoom() <= provinceScaleLevel) {
            cloudDataLayer.setMap(null);
            isSubMarkersShow = false;
            isSearchShow = false;
            search.clear();
            mapProvinceSet();
        } else {
            if (!isSubMarkersShow && !isSearchShow) {
                mapCitySet();
            }
        }
    });

    //设置城市
    AMap.event.addDomListener(document.getElementById('query'), 'click', function () {
        var cityName = document.getElementById('cityName').value;
        if (!cityName) {
            cityName = '上海市';//默认指定城市
        }
        map.setCity(cityName);
    });

    //查询小区
    AMap.event.addDomListener(document.getElementById('communitySearch'),'click',function(){
        var communityName = document.getElementById('communityName').value;
        if(!communityName){
            communityName = '上海';//默认指定小区
        }

        cloudDataLayer.setMap(null);
        map.clearMap();
        //加载CloudDataSearch服务插件
        AMap.service(["AMap.CloudDataSearch"], function() {
            isSearchShow = true;
            var searchOptions = {
                map:map,
                panel:'panel',
                keywords:communityName,
                pageSize:5,
                orderBy:'_id:ASC'
            };
            search = new AMap.CloudDataSearch(tableId, searchOptions);

            search.searchByDistrict("全国",function(status,cloudDataSearchResult){
                console.log(status,cloudDataSearchResult);
            })
        });

    });

    //地图绘制完成
    map.on('complete', function () {

        //地图初始化
        mapInit();
        mapCommunityCloudInit();

    });

    var contextMenu = new AMap.ContextMenu();  //创建右键菜单
    //右键放大
    contextMenu.addItem("放大一级", function () {
        map.zoomIn();
    }, 0);
    //右键缩小
    contextMenu.addItem("缩小一级", function () {
        map.zoomOut();
    }, 1);

    contextMenu.addItem("清行政界", function (e) {
        map.remove(polygons);
    }, 3);

    //地图绑定鼠标右击事件——弹出右键菜单
    map.on('rightclick', function (e) {
        contextMenu.open(map, e.lnglat);
        contextMenuPositon = e.lnglat;
    });
</script>
</body>
</html>